/**
 * @description 上传组件封装
 */
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Modal, Upload, message } from 'antd';
import http from '@/utils/http';

import { useImperativeHandle } from 'react';
import { UPLOADIMG_API } from '@/api';

const XxUpload = ({
    accept = 'image/png,image/jpg,image/jpeg',
    maxCount = 1,
    multiple = true,
    defalutFileList = [],
    onRef,
    setState = () => { }
}) => {
    const [fileList, setFileList] = useState([]);
    const handleChange = ({ file, fileList: newFileList }) => {
        setFileList(newFileList)
        console.log("onChange事件触发", newFileList)
        if (file.status === 'uploading') {
            // setLoading(true);
            return;
        }
        if (file.status === 'done') {
            // setLoading(false)
            setState(newFileList)
        }
        if (file.status === 'removed') {
            setState(newFileList)
        }
    };


    useImperativeHandle(onRef, () => ({
        setFileList,
    }))
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传
            </div>
        </div>
    );
    const customRequest = async (params) => {
        const { file, onSuccess, onError } = params;
        http.upload({
            url: UPLOADIMG_API,
            params: {
                file: file,
                filename: 'file',
            },
            before: () => { },
            success: (res) => {
                if (res.status === "0000") {
                    console.log("图片上传成功", res)
                    const { url, uid, name } = res?.data
                    onSuccess({ url, uid, name })
                } else {
                    message.error(res.responseMsg)
                    onError()
                }
            },
            failure: (msg) => {
                message.error("图片上传失败：" + msg)
                onError()
            },
            complete: () => { }
        })

    }
    return (
        <>
            <>
                <Upload
                    accept={accept}
                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    listType="picture-card"
                    showUploadList={{ showPreviewIcon: false }}
                    fileList={fileList}
                    onChange={handleChange}
                    maxCount={maxCount}
                    customRequest={customRequest}
                    multiple={multiple}

                >
                    {fileList.length >= maxCount ? null : uploadButton}
                </Upload>

            </>

        </>
    );
}

export default XxUpload;